package com.webside.points.wechat;


import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.webside.points.model.UserEntity;
import com.webside.points.model.UserPostEntity;
import com.webside.points.service.UserPostService;
import com.webside.points.service.UserService;
import com.webside.points.service.impl.UserPostServiceImpl;
import com.webside.points.service.impl.UserServiceImpl;




/**
 * 支付结果通知回调处理类
 * 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
 * @author apple
 *
 */
public class StudyResultNotify extends Notify {

	
	public StudyResultNotify(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}

	@Override
	public void ProcessNotify() throws NoSuchAlgorithmException,
			WxPayException, IOException, ParserConfigurationException,
			SAXException {
		WxPayData notifyData = GetNotifyData();
		
		// 检查支付结果中transaction_id是否存在
		if (!notifyData.IsSet("transaction_id")) {
			// 若transaction_id不存在，则立即返回结果给微信支付后台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "FAIL");
			res.SetValue("return_msg", "支付结果中微信订单号不存在");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
		}

		String transaction_id = notifyData.GetValue("transaction_id")
				.toString();

		// 查询订单，判断订单真实性
		if (!QueryOrder(transaction_id)) {
			// 若订单查询失败，则立即返回结果给微信支付后台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "FAIL");
			res.SetValue("return_msg", "订单查询失败");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
		}else {
			// 查询订单成功
			//更新用户的金额
			
			//修改付款金额
			String total_fee = (String) notifyData.GetValue("total_fee");
			//付款用户openId
			String openid = (String) notifyData.GetValue("openid");
			String attach = (String) notifyData.GetValue("attach");
			
			System.out.println("学习支付成功：>>>"+total_fee+ "  " + openid +" "+attach);
			
			String array[]=attach.split(";");
			
			UserPostService userPostService = UserPostServiceImpl.getInstance();
			UserPostEntity userPostEntity = userPostService.findByTransactionId(transaction_id);
			System.out.println("userPostEntity>>>:"+userPostEntity);
			if(userPostEntity==null){
				//增加用户购买信息
				UserPostEntity updateUserPostEntity = new UserPostEntity();
				updateUserPostEntity.setTransactionId(transaction_id);
				updateUserPostEntity.setUserId(Integer.valueOf(array[0]));
				updateUserPostEntity.setPostTypeId(Integer.valueOf(array[1]));
				updateUserPostEntity.setCreateTime(new Date(System.currentTimeMillis()));
				userPostService.insert(updateUserPostEntity);
				//更新用户付款金额
				UserService userService=UserServiceImpl.getInstance();
				UserEntity user = userService.findByOpenId(openid);
				UserEntity userEntity=new UserEntity();
				double amount=user.getPayment();
				amount=amount+Util.centTurnAmount(total_fee);
				userEntity.setPayment(amount);
				userEntity.setOpenId(openid);
				userService.updatePayment(userEntity);
			}
			
			
			//通知微信平台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "SUCCESS");
			res.SetValue("return_msg", "OK");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
			
		}
	}

	// 查询订单
	private boolean QueryOrder(String transaction_id)
			throws NoSuchAlgorithmException, WxPayException,
			ParserConfigurationException, SAXException, IOException {
		WxPayData req = new WxPayData();
		req.SetValue("transaction_id", transaction_id);
		WxPayData res = WxPayApi.OrderQuery(req, 0);
		if (res.GetValue("return_code").toString().equalsIgnoreCase("SUCCESS")
				&& res.GetValue("result_code").toString()
						.equalsIgnoreCase("SUCCESS")) {
			return true;
		} else {
			return false;
		}
	}

}
